package com.concurrence;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * TwinsLock..
 *
 * @author Lizhong
 * @date 2019/4/4
 */
public class TwinsLock implements Lock {
    private Sync sync = new Sync(2);

    private class Sync extends AbstractQueuedSynchronizer {
        Sync(int count) {
            // 运行时异常不需要捕获
            if (count <= 0) throw new IllegalArgumentException("不合法的输入:" + count);
            setState(count);
        }

        @Override
        protected int tryAcquireShared(int arg) {
            for (; ; ) {
                int state = this.getState();
                int newState = state - arg;
                if (newState >=0 && compareAndSetState(state, newState)) {
                    return newState;
                }
            }
        }

        @Override
        protected boolean tryReleaseShared(int arg) {
            for (; ; ) {
                int state = this.getState();
                int newState = state + arg;
                if (compareAndSetState(state, newState)) {
                    return true;
                }

            }
        }
    }

    @Override
    public void lock() {
        sync.tryAcquireShared(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public void unlock() {
        sync.tryReleaseShared(1);
    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
